<template>
    <div class="system-container">
      <div class="main-content">
        <!-- 左侧订单详情 -->
        <div class="left-panel">
          <!-- 餐台信息 -->
          <div class="section-title">餐台信息</div>
          <div class="table-info-grid">
            <div>餐台编号:{{ currentOrder.table?.tableId }}</div>
            <div>就餐人数:{{ currentOrder.peopleCount }}</div>
            <div>订单ID:{{ currentOrder.orderId }}</div>
          </div>
  
          <!-- 菜品信息 -->
          <div class="section-title">菜品信息</div>
          <el-table :data="currentOrder.dishes" class="dish-table">
            <el-table-column prop="id" label="序号" width="80"/>
            <el-table-column prop="dish.dishName" label="菜品名称"/>
            <el-table-column prop="quantity" label="数量" width="100"/>
            <!-- <el-table-column prop="originalPrice" label="原价" width="120">
              <template #default="{row}">￥{{ row.originalPrice }}</template>
            </el-table-column>
            <el-table-column prop="currentPrice" label="现价" width="120">
              <template #default="{row}">￥{{ row.currentPrice }}</template>
            </el-table-column>
            <el-table-column prop="discount" label="折扣" width="120">
              <template #default="{row}">{{ row.discount || '-' }}</template>
            </el-table-column> -->
            <el-table-column label="单价" width="120">
            <template #default="{row}">￥{{ row.dish.dishPrice }}</template>
          </el-table-column>
          <el-table-column label="小计" width="120">
            <template #default="{row}">
              ￥{{ (row.dish.dishPrice * row.quantity).toFixed(2) }}
            </template>
          </el-table-column>
          </el-table>
  
          <!-- 订单信息 -->
          <div class="section-title">订单信息</div>
          <div class="order-info-grid">
            <div class="info-item">
              <span class="label">订单状态：</span>
              <!-- <el-tag type="warning">结账中</el-tag> -->
              <el-tag :type="getStatusTagType(currentOrder.orderStatus)">
              {{ currentOrder.orderStatus }}
            </el-tag>
            </div>
            <div class="info-item">
              <span class="label">下单时间：</span>
              <span>{{ formatTime(currentOrder.orderTime) }}</span>
            </div>
          </div>
  
          <!-- 整单备注 -->
          <div class="section-title">整单备注</div>
          <div class="order-remarks">
            <el-input 
              type="textarea" 
              :rows="2" 
              placeholder="备注信息" 
              :model-value="currentOrder.remarks" 
              readonly
            />
          </div>
        </div>
  
        <!-- 右侧支付区域 -->
        <div class="right-panel">
          <div class="section-title">支付信息</div>
          
          <!-- 支付方式 -->
          <div class="payment-methods">
            <el-radio-group v-model="selectedPayment">
              <el-radio 
                v-for="method in paymentMethods" 
                :key="method" 
                :label="method"
                class="payment-card"
              >
                {{ method }}
              </el-radio>
            </el-radio-group>
          </div>
  
          <!-- 优惠券 -->
          <div v-if="selectedPayment === '团购验券'" class="coupon-section">
            <el-input
            v-model="couponCode"
              placeholder="请扫描或输入团购券码"
              :class="{ 'error': couponError }"
              @change="validateCoupon"
            >
              <template #append>
                <el-button icon="el-icon-scan">扫码</el-button>
              </template>
            </el-input>
            <!-- 券码错误提示 -->
    <div v-if="couponError" class="error-tip">
      <el-icon><warning /></el-icon>
      {{ couponError }}
    </div>
          </div>
  
          <!-- 金额汇总 -->
          <div class="amount-summary">
            <div class="amount-item">
              <span>订单原价</span>
              <span>￥{{ currentOrder.orderAmount?.toFixed(2) }}</span>
            </div>
            <div class="amount-item discount">
              <span>优惠金额</span>
              <span>-￥{{ currentOrder.discountAmount?.toFixed(2) || '0.00' }}</span>
            </div>
            <div class="amount-item total">
              <span>实收金额</span>
              <span>￥{{ currentOrder.receivedAmount?.toFixed(2) }}</span>
            </div>
          </div>
  
          <div class="payment-input">
      <!-- 微信/支付宝显示金额 -->
      <el-input 
        v-if="['微信支付', '支付宝'].includes(selectedPayment)"
        :model-value="currentOrder.receivedAmount?.toFixed(2)"
        readonly
        class="amount-display"
      >
        <template #prefix>
          <span class="currency-symbol">￥</span>
        </template>
      </el-input>

      <!-- 现金支付输入区域 -->
      <template v-if="selectedPayment === '现金'">
        <el-input
          v-model="cashAmount"
          placeholder="请输入实收金额"
          class="cash-input"
          @input="validateCash"
        >
          <template #prefix>
            <span class="currency-symbol">￥</span>
          </template>
        </el-input>
        <div class="change-section">
          <span>找零金额：</span>
          <span class="change-amount">￥{{ changeAmount }}</span>
        </div>
        <!-- 现金错误提示 -->
    <div v-if="cashError" class="error-tip">
      <el-icon><warning /></el-icon>
      {{ cashError }}
    </div>
      </template>
    </div>


          <!-- 操作按钮 -->
          <div class="action-buttons">
            <el-button class="cancel-btn" size="large" @click="router.back()">取消支付</el-button>
            <el-button type="primary" class="confirm-btn" size="large" @click="handlePayment" :loading="isPaying">结账完成</el-button>
          </div>
        </div>
      </div>
    </div>
  </template>
  
  <script setup lang="ts">
  import { ref, computed, watch, onMounted } from 'vue'
  import { Warning } from '@element-plus/icons-vue'
  import { useRoute, useRouter } from 'vue-router'
  import { ElMessage } from 'element-plus'
import type { OrderDTO } from '@/views/order/management/types'
import { getOrderById, updateOrder } from '@/api/order'
import { listAllTable, updateTable } from '@/api/table'

  const route = useRoute()
  const router = useRouter()
  
// 当前订单数据
const currentOrder = ref<OrderDTO>({
  orderId: '',
  table: { tableId: '', tableType: '', tableStatus: '' },
  peopleCount: 0,
  dishes: [],
  orderAmount: 0,
  discountAmount: 0,
  receivedAmount: 0,
  orderTime: '',
  payTime: '',
  orderStatus: '待支付',
  paymentMethod: undefined,
  remarks: ''
})
  
  // 支付相关
  const paymentMethods = ['微信支付', '支付宝', '现金', '团购验券']
  const selectedPayment = ref('微信支付')
  const isPaying = ref(false)

  // 新增现金支付相关状态
const cashAmount = ref('')
const cashError = ref('')

// 优惠券相关
const couponCode = ref('')
const couponError = ref('')

// 计算找零
const changeAmount = computed(() => {
  const paid = parseFloat(cashAmount.value) || 0
  return (paid - currentOrder.value.receivedAmount).toFixed(2)
})

// 初始化加载订单数据
onMounted(async () => {
  const orderId = route.params.orderId as string
  if (!orderId) {
    ElMessage.error('无效的订单ID')
    router.back()
    return
  }

  try {
    const res = await getOrderById(orderId)
    currentOrder.value = res.data
    // 计算实收金额
    currentOrder.value.receivedAmount = 
      currentOrder.value.orderAmount - (currentOrder.value.discountAmount || 0)
  } catch (error) {
    ElMessage.error('订单加载失败')
    console.error(error)
    router.back()
  }
})

// 支付方式过滤（根据订单类型）
const validPaymentMethods = computed(() => {
  return paymentMethods.filter(m => 
    m !== '团购验券' || currentOrder.value.paymentMethod === '团购'
  )
})

// 支付处理
const handlePayment = async () => {
  try {
    isPaying.value = true
    
    // 更新订单状态
    const updatedOrder: OrderDTO = {
      ...currentOrder.value,
      orderStatus: '已支付',
      paymentMethod: selectedPayment.value,
      payTime: new Date().toISOString()
    }
    // 更新订单
    await updateOrder(updatedOrder)

    // 更新桌台状态
    // const tables = await listAllTable()
    // const table = tables.data.find((t: { tableId: string }) => t.tableId === updatedOrder.table.tableId)
    // if (table) {
    //   table.tableStatus = '空闲'
      // 这里需要调用更新桌台的API
    // }
    const tableToUpdate = { 
      ...currentOrder.value.table,
      tableStatus: '空闲'
    }
    await updateTable(tableToUpdate)

    
    ElMessage.success('支付成功')
  } catch (error) {
    ElMessage.error('支付失败')
    console.error(error)
  } finally {
    isPaying.value = false
  }
}

// 状态标签样式
const getStatusTagType = (status: string) => {
  switch (status) {
    case '待支付': return 'warning'
    case '已支付': return 'success'
    default: return 'info'
  }
}

// 时间格式化
const formatTime = (isoString: string) => {
  return new Date(isoString).toLocaleString()
}

// 现金验证逻辑
const validateCash = () => {
  const value = parseFloat(cashAmount.value)
  const amount = parseFloat(realTimeAmount.value)
  if (isNaN(value)) {
    cashError.value = '请输入有效金额'
    return false
  }
  if (value < currentOrder.value.receivedAmount) {
    cashError.value = `金额不足，还需￥${(currentOrder.value.receivedAmount - value).toFixed(2)}`
    return false
  }
  cashError.value = ''
  return true
}

// 券码验证逻辑
const validateCoupon = async () => {
  if (!/^[A-Z0-9]{16}$/.test(couponCode.value)) {
    couponError.value = "券码格式不正确"
    return false
  }
  // 实际应调用券码验证接口
  return true
}




const realTimeAmount = ref('146.00') // 从订单信息获取

// 切换支付方式时重置现金输入
watch(selectedPayment, (newVal) => {
  if (newVal !== '现金') {
    cashAmount.value = ''
  }
})

// 模拟券码验证API
const mockValidateCoupon = (code: string) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(code === "DEMO20250310ABCDE") // 模拟有效券码
    }, 500)
  })
}
  </script>
  
  <style scoped>
  .system-container {
    height: 100vh;
    background: #f5f7fa;
    padding: 20px;
  }
  
  .main-content {
    display: flex;
    height: calc(100vh - 40px);
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0,0,0,0.1);
  }
  
  .left-panel {
    flex: 1;
    padding: 20px;
    border-right: 1px solid #ebeef5;
    min-width: 550px;
  }
  
  .right-panel {
    width: 450px;
    padding: 20px;
  }
  
  .section-title {
    font-size: 16px;
    font-weight: 600;
    color: #303133;
    margin-bottom: 15px;
    padding-bottom: 10px;
    border-bottom: 2px solid #e4e7ed;
  }
  
  .table-info-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 12px;
    margin-bottom: 20px;
    div {
      padding: 8px;
      background: #f8f9fa;
      border-radius: 4px;
    }
  }
  
  .dish-table {
    margin: 15px 0;
    :deep(.el-table__header th) {
      background: #f8f9fa;
    }
  }
  
  .order-info-grid {
    display: grid;
    gap: 12px;
    margin: 15px 0;
    .info-item {
      display: flex;
      align-items: center;
      .label {
        color: #909399;
        margin-right: 8px;
      }
    }
  }
  
  .payment-methods {
    margin: 20px 0;
    .payment-card {
      display: block;
      margin: 8px 0;
      padding: 12px;
      border-radius: 4px;
      border: 1px solid #dcdfe6;
      &:hover {
        border-color: #409eff;
      }
    }
  }
  
  .coupon-section {
    margin: 20px 0;
    .coupon-input {
      :deep(.el-input-group__append) {
        padding: 0 15px;
      }
    }
  }
  
  .amount-summary {
    margin: 25px 0;
    .amount-item {
      display: flex;
      justify-content: space-between;
      padding: 8px 0;
      &.discount {
        color: #67c23a;
      }
      &.total {
        font-size: 16px;
        font-weight: 600;
        color: #f56c6c;
        border-top: 1px solid #ebeef5;
        padding-top: 12px;
      }
    }
  }
  
  .action-buttons {
    display: grid;
    grid-template-columns: 1fr 2fr;
    gap: 15px;
    .cancel-btn {
      background: #f0f2f5;
      color: #606266;
    }
    .confirm-btn {
      width: 100%;
    }
  }
  
  .order-remarks {
    margin-top: 20px;
    :deep(.el-textarea__inner) {
      background: #f8f9fa;
    }
  }

  /* 新增样式 */
.payment-input {
  margin: 20px 0;
}

.amount-display :deep(.el-input__inner) {
  background-color: #f5f7fa;
  color: #606266;
}

.cash-input {
  margin-bottom: 12px;
}

.change-section {
  display: flex;
  justify-content: space-between;
  padding: 8px 12px;
  background: #f8f9fa;
  border-radius: 4px;
}

.change-amount {
  color: #67c23a;
  font-weight: 500;
}

.currency-symbol {
  color: #f56c6c;
  margin-right: 5px;
}

/* 错误提示样式 */
.error-tip {
  color: #f56c6c;
  font-size: 12px;
  margin-top: 4px;
  display: flex;
  align-items: center;
  gap: 4px;
}

/* 错误状态输入框 */
:deep(.error .el-input__inner) {
  border-color: #f56c6c;
}

/* 现金输入框间距调整 */
.cash-input {
  margin-bottom: 8px;
}
  </style>